#!/bin/bash

PACKAGE_PATH="$1"
INSTALL_PATH="$2"
INSTALL_VOLUME="$3"
SYSTEM_ROOT="$4"

# The purpose of the postflight script is to make sure that a valid driver
# settings file exists after the package has been installed.

PREFERENCES_DIR="${INSTALL_VOLUME}/Library/Preferences"
FSBUNDLE_DIR="${INSTALL_VOLUME}/Library/Filesystems/tuxera_ntfs.fs"
SETTINGS_PLIST_PFX="${PREFERENCES_DIR}/com.tuxera.NTFS"
TEMPLATE_SETTINGS_PLIST_PFX="${FSBUNDLE_DIR}/Contents/Resources/Support/standard_defaults"
SETTINGS_PLIST="${SETTINGS_PLIST_PFX}.plist"
TEMPLATE_SETTINGS_PLIST="${TEMPLATE_SETTINGS_PLIST_PFX}.plist"
PACKAGE_NAME="TuxeraNTFS.pkg"
APPLICATION_SUPPORT_DIR="/Library/Application Support/Tuxera NTFS"
BACKUP_RECEIPT_PATH="${APPLICATION_SUPPORT_DIR}/Receipt.bom"

PLISTKEY_DISABLE_DRIVER="DisableDriver"
PLISTKEY_ENABLE_RAW_DEVICES="EnableRawDevices"
PLISTKEY_ENABLE_CACHING="EnableCaching"
PLISTKEY_ENABLE_NORMALIZATION="EnableNormalization"
PLISTKEY_ENABLE_AUTOMATIC_RECOVERY="EnableAutomaticRecovery"
PLISTKEY_DISABLE_REMOVE_HIBERFILE="DisableRemoveHiberfile"
PLISTKEY_XATTR_MODE="XattrMode"
PLISTKEY_ENABLE_SFM_CONVERSIONS="EnableSFMConversions"
PLISTKEY_LOGGING_LEVEL="LoggingLevel"

MENUBARAGENT_PATH="/Library/Filesystems/tuxera_ntfs.fs/Contents/Resources/Support/TuxeraMenuBarAgent/Tuxera NTFS.app"

# Fills a plist value from a specified key, reading the value from the template file.
FillPlistValueFromDefaults() {
    PLISTKEY="$1"
    DEFAULTS_OUTPUT=`defaults read "${TEMPLATE_SETTINGS_PLIST_PFX}" "${PLISTKEY}"`
    DEFAULTS_RETVAL=$?
    if [ ! ${DEFAULTS_RETVAL} -eq 0 ]; then
	echo "[ERROR] Couldn't read key \"${PLISTKEY}\" from \"${TEMPLATE_SETTINGS_PLIST_PFX}\"."
	exit 1
    else
	PLISTVALUE="${DEFAULTS_OUTPUT}"
	DEFAULTS_OUTPUT=`defaults write "${SETTINGS_PLIST_PFX}" "${PLISTKEY}" "${PLISTVALUE}"`
	DEFAULTS_RETVAL=$?
	if [ ! ${DEFAULTS_RETVAL} -eq 0 ]; then
	    echo "[ERROR] Could not write defaults value for ${PLISTKEY}. Command:"
	    echo "          defaults write \"${SETTINGS_PLIST_PFX}\" "
	    echo "            \"${PLISTKEY}\" \"${PLISTVALUE}\""
	    echo "        failed with error code: ${DEFAULTS_RETVAL}"
	    exit 1
	fi
    fi
}

# Checks if a value exists in the settings .plist, and if it doesn't it is
# filled in from the default settings file.
FillPlistValueIfNeeded() {
    DEFAULTS_OUTPUT=`defaults read "${SETTINGS_PLIST_PFX}" "$1"`
    DEFAULTS_RETVAL=$?
    if [ ! ${DEFAULTS_RETVAL} -eq 0 ]; then
	FillPlistValueFromDefaults "$1"
    fi
}

# Entry point

# Copy the .bom file to the application support directory.
if [ ! -d "${APPLICATION_SUPPORT_DIR}" ]; then
    mkdir -p "${APPLICATION_SUPPORT_DIR}"
    if [ $? -ne 0 ]; then
	echo "[ERROR] Unable to create application support directory \"${APPLICATION_SUPPORT_DIR}\"."
	exit 1
    fi
fi

chflags nouchg "${APPLICATION_SUPPORT_DIR}"
chmod 0755 "${APPLICATION_SUPPORT_DIR}"

if [ -f "${BACKUP_RECEIPT_PATH}" ]; then
    chflags nouchg "${BACKUP_RECEIPT_PATH}"
    rm -f "${BACKUP_RECEIPT_PATH}"
    if [ $? -ne 0 ]; then
	echo "[ERROR] Unable to remove existing backup receipt \"${BACKUP_RECEIPT_PATH}\"."
	exit 1
    fi
fi

if [ -d "${PACKAGE_PATH}" ]; then
    cp "${PACKAGE_PATH}/Contents/Archive.bom" "${BACKUP_RECEIPT_PATH}"
    if [ ! $? -eq 0 ]; then
	echo "[ERROR] Couldn't copy BOM file ${PACKAGE_PATH}/Contents/Archive.bom to ${BACKUP_RECEIPT_PATH}."
	exit 1
    fi
else
    BOM_TEMPDIR=`mktemp -d "/tmp/tuxera_ntfs_for_mac_installer_XXXXXX"`
    if [ ! $? -eq 0 ]; then
	echo "[ERROR] Couldn't create temporary directory for BOM file extraction."
	exit 1
    fi

    pushd "${BOM_TEMPDIR}" > /dev/null

    xar -x -f "${PACKAGE_PATH}" "${PACKAGE_NAME}/Bom"
    if [ ! $? -eq 0 ]; then
	echo "[ERROR] Couldn't extract BOM file ${PACKAGE_NAME}/Bom to ${BOM_TEMPDIR}."
	rm -rf "${BOM_TEMPDIR}"
	exit 1
    fi

    popd > /dev/null

    mv "${BOM_TEMPDIR}/${PACKAGE_NAME}/Bom" "${BACKUP_RECEIPT_PATH}"
    if [ ! $? -eq 0 ]; then
	echo "[ERROR] Couldn't move extracted file (${BOM_TEMPDIR}/${PACKAGE_NAME}/Bom) to proper location (${BACKUP_RECEIPT_PATH})."
	rm -rf "${BOM_TEMPDIR}"
	exit 1
    fi

    rm -rf "${BOM_TEMPDIR}"
    if [ ! $? -eq 0 ]; then
	echo "[ERROR] Error while deleting temporary directory ${BOM_TEMPDIR}."
	exit 1
    fi
fi

chmod 0444 "${BACKUP_RECEIPT_PATH}"
chflags uchg "${BACKUP_RECEIPT_PATH}"
chmod 0555 "${APPLICATION_SUPPORT_DIR}"

# If the settings file doesn't exist, create it from the default template.
#if [ ! -f "${SETTINGS_PLIST}" ]; then
#    # Cleanup, in case someone is playing a trick on us...
#    rm -rf "${SETTINGS_PLIST}"
#    if [ ! $? -eq 0 ]; then
#	echo "[ERROR] Failed to remove existing contents at location: ${SETTINGS_PLIST}"
#	exit 1
#    fi
#
#     # Copy the template to the location of the settings .plist.
#    cp -f "${TEMPLATE_SETTINGS_PLIST}" "${SETTINGS_PLIST}"
#    if [ ! $? -eq 0 ]; then
#	echo "[ERROR] Couldn't create a default settings file for NTFS-3G!"
#	exit 1
#    fi
#fi

if [ -f "${SETTINGS_PLIST}" ]; then
    # Make sure that the existing settings plist file is not locked (uchg flag).
    chflags nouchg "${SETTINGS_PLIST}"
fi

# These values should be written unconditionally
FillPlistValueFromDefaults "${PLISTKEY_DISABLE_DRIVER}"
FillPlistValueFromDefaults "${PLISTKEY_ENABLE_RAW_DEVICES}"

# Fill in any gaps that might exist in the settings file.
FillPlistValueIfNeeded "${PLISTKEY_ENABLE_CACHING}"
FillPlistValueIfNeeded "${PLISTKEY_ENABLE_NORMALIZATION}"
FillPlistValueIfNeeded "${PLISTKEY_ENABLE_AUTOMATIC_RECOVERY}"
FillPlistValueIfNeeded "${PLISTKEY_DISABLE_REMOVE_HIBERFILE}"
FillPlistValueIfNeeded "${PLISTKEY_XATTR_MODE}"
FillPlistValueIfNeeded "${PLISTKEY_ENABLE_SFM_CONVERSIONS}"
FillPlistValueIfNeeded "${PLISTKEY_LOGGING_LEVEL}"


# Make sure the settings file has the appropriate value of MountRdisks for this
# build.
TEMPLATE_RDISKS_VALUE=`defaults read "${TEMPLATE_SETTINGS_PLIST_PFX}" ${PLISTKEY_ENABLE_RAW_DEVICES}`
DEFAULTS_RETVAL=$?
if [ ! ${DEFAULTS_RETVAL} -eq 0 ]; then
    echo "[ERROR] Invoking 'defaults read \"${TEMPLATE_SETTINGS_PLIST_PFX}\" ${PLISTKEY_ENABLE_RAW_DEVICES}' failed with error code: ${DEFAULTS_RETVAL}"
    exit 1
elif ( [[ ${TEMPLATE_RDISKS_VALUE} -eq 0 ]] || [[ ${TEMPLATE_RDISKS_VALUE} -eq 1 ]] ); then
    defaults write "${SETTINGS_PLIST_PFX}" ${PLISTKEY_ENABLE_RAW_DEVICES} ${TEMPLATE_RDISKS_VALUE}
    DEFAULTS_RETVAL=$?
    if [ ! ${DEFAULTS_RETVAL} -eq 0 ]; then
	echo "[ERROR] Could not write new defaults value for ${PLISTKEY_ENABLE_RAW_DEVICES}. Command:"
	echo "          defaults write \"${SETTINGS_PLIST_PFX}\" ${PLISTKEY_ENABLE_RAW_DEVICES} ${TEMPLATE_RDISKS_VALUE}"
	echo "        failed with error code: ${DEFAULTS_RETVAL}"
	exit 1
    fi
else
    echo "[ERROR] Unrecognized value for '${PLISTKEY_ENABLE_RAW_DEVICES}': ${TEMPLATE_RDISKS_VALUE}"
    exit 1
fi


# As a precaution, reset the mode and owner/group for the settings file
# unconditionally.
chown root:admin "${SETTINGS_PLIST}"
if [ ! $? -eq 0 ]; then
    echo "[ERROR] Couldn't set ownership for ${SETTINGS_PLIST}."
    exit 1
fi
chmod 644 "${SETTINGS_PLIST}"
if [ ! $? -eq 0 ]; then
    echo "[ERROR] Couldn't set mode for ${SETTINGS_PLIST}."
    exit 1
fi

# Launch menu bar agent.
open "${MENUBARAGENT_PATH}"

# Execution was successful.
exit 0
